<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.js"></script>
</head>
<body>
    <div>
        请输入用户名：<input type="text" id="username"/>
    </div>
    <div>
        请输入密码：  <input type="password" id="password"/>
    </div>
    <div>
        <button id="btn1">登录</button>
    </div>
    <div id="result">

    </div>
</body>
<script type="text/javascript">
    $(document).ready(function (){
        var token;
        $("#btn1").click(function (){
            var username=$("#username").val();
            var password=$("#password").val();

            $.ajax({
                type: 'post',
                url: 'http://localhost:8090/user/login',
                contentType: 'application/json',
                dataType: 'json',
                data: JSON.stringify({
                    "username": username,
                    "password": password
                }),

                xhrFields: {
                    withCredentials: true // 发送Ajax时，Request header中会带上 Cookie 信息。
                },

                function:setCookie("access_token","qwertyuiop",1),


                success: function (data){
                    console.log(data)
                    if(data.code == 200){
                        alert('登录成功');
                        //$("#result").text("登录成功！")
                        token = data.result.token; //获得token
                        //对localStorage进行操作
                        console.log("localStorage success")
                        localStorage.setItem("token", token)
                        localStorage.setItem("username", username)
                        console.log(localStorage.getItem("token"))
                        console.log(localStorage.getItem("username"))
                        //跳转欢迎页面
                        window.location.href = "welcome.html"
                    }else{
                        alert('登录失败' + data.message)
                    }
                },
                error: function (){
                    alert('参数错误')
                }
            })
        })
    })

    // 设置cookie
    function setCookie(c_name, value, expiredays) {
        var exdate = new Date();
        exdate.setDate(exdate.getDate() + expiredays);
        document.cookie =
            c_name +
            '=' +
            encodeURIComponent(value) +
            ';expires=' +
            exdate.toGMTString() +
            ';path=/';
    }


</script>


</html>